﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Core.Utility.Extensions
{
    /// <summary>
    /// 日期格式化 斜线风格，格式化 yyyy/MM/dd
    /// 
    /// <code>用法： [JsonConverter(typeof(DateTimeSlashStyleFormatConverter))]</code>
    /// </summary>
    public class DateTimeSlashStyleFormatConverter : IsoDateTimeConverter
    {
        /// <summary>
        /// 默认日期格式
        /// </summary>
        public DateTimeSlashStyleFormatConverter() { DateTimeFormat = "yyyy/MM/dd HH:mm:ss"; }
        /// <summary>
        /// 日期格式
        /// </summary>
        public DateTimeSlashStyleFormatConverter(string format) { DateTimeFormat = format; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="objectType"></param>
        /// <returns></returns>
        public override bool CanConvert(Type objectType)
        {
            return (objectType == typeof(DateTime)) || (objectType == typeof(DateTime?)) || (objectType == typeof(string));
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="t"></param>
        /// <param name="existingValue"></param>
        /// <param name="serializer"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null) return null;
            var value = serializer.Deserialize<string>(reader);
            DateTime d;
            if (DateTime.TryParse(value, out d))
            {
                return d;
            }
            else
            {
                return null;
            }
            throw new Exception("Cannot unmarshal type long");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="value"></param>
        /// <param name="serializer"></param>
        public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
        {
            DateTime? date = (DateTime?)value;
            string format = "yyyy/MM/dd";
            //if (date?.Hour == 0 &&
            //    date?.Minute == 0 &&
            //    date?.Second == 0 &&
            //    date?.Millisecond == 0)
            //{
            //    format = "yyyy-MM-dd";
            //}
            writer.WriteValue(date?.ToString(format));
        }

        /// <summary>
        /// 
        /// </summary>
        public override bool CanRead => false;
    }
}
